
import os
import sys
sys.path.append(os.path.dirname(__file__))
from custom.stackedWidget import StackedWidget
from custom.listWidgets import FuncListWidget, UsedListWidget
from custom.graphicsView import GraphicsView
import cv2
from universal.root_path import scanAllImages
from PyQt5.QtWidgets import *
import qdarkstyle
import glob
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QRect,Qt
import matplotlib.pyplot as plt
from universal.commom_widget.Tabwidget import TabWidget
from universal.commom_widget.Tablewidget import Tablewidget
from universal.commom_widget.commonWidgetFunction import setAct
import numpy as np
__appname__ = '章鱼博士'
class MyApp(QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()
        # self.tool_bar = self.addToolBar('工具栏')
        self.action_right_rotate = QAction(QIcon("icons/右旋转.png"), "向右旋转90", self)
        self.action_left_rotate = QAction(QIcon("icons/左旋转.png"), "向左旋转90°", self)
        self.action_histogram = QAction(QIcon("icons/直方图.png"), "直方图", self)
        self.action_right_rotate.triggered.connect(self.right_rotate)
        self.action_left_rotate.triggered.connect(self.left_rotate)
        self.action_histogram.triggered.connect(self.histogram)
        # self.tool_bar.addActions((self.action_left_rotate, self.action_right_rotate, self.action_histogram))

        self.useListWidget = UsedListWidget(self)
        self.funcListWidget = FuncListWidget(self)
        self.stackedWidget = StackedWidget(self)
        self.graphicsView = GraphicsView(self)#

        self.dock_file = QDockWidget(self)
        self.ImgTable = self.LoadImg()
        self.dock_file.setTitleBarWidget(QWidget())
        self.leftwidget = TabWidget([self.ImgTable],["图像加载"])
        self.dock_file.setWidget(self.leftwidget)
        self.dock_file.setFeatures(QDockWidget.NoDockWidgetFeatures)

        self.dock_func = QDockWidget(self)
        self.dock_func.setWidget(self.funcListWidget)
        self.dock_func.setTitleBarWidget(QLabel('图像操作'))
        self.dock_func.setFeatures(QDockWidget.NoDockWidgetFeatures)

        self.addToolBarBreak(area=Qt.RightToolBarArea)
        self.dock_used = QDockWidget()
        self.dock_used.setWidget(self.useListWidget)
        self.dock_used.setTitleBarWidget(QLabel('已选操作'))
        self.dock_used.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.dock_used.setFeatures(QDockWidget.NoDockWidgetFeatures)

        self.dock_attr = QDockWidget(self)
        self.dock_attr.setWidget(self.stackedWidget)
        self.dock_attr.setTitleBarWidget(QLabel('属性'))
        self.dock_attr.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.dock_attr.close()

        self.setCentralWidget(self.graphicsView)
        # self.addDockWidget(Qt.LeftDockWidgetArea, self.dock_file)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_func,True)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_used,True)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock_attr)

        self.setWindowTitle('Opencv图像处理')
        self.setWindowIcon(QIcon('icons/main.png'))
        self.src_img = None
        self.cur_img = None

    def LoadImg(self):
        ImgTable = Tablewidget(2, 2)
        name_list = ["图像路径","当前图像"]
        ImgTable.Tablewidget_setItem(name_list)
        self.imgspath, actLineImg = setAct(self, ':/icons/1-1.ico')
        self.showImg = QLineEdit()
        self.showImg.setReadOnly(True)
        actLineImg.triggered.connect(lambda: self.getSavePath())
        TabelParameter_Input_list = [self.imgspath,self.showImg]
        ImgTable.SetCellWidget(TabelParameter_Input_list)

        self.graphicsView.buttonRight.clicked.connect(self.openNextImg)
        self.graphicsView.buttonLeft.clicked.connect(self.openPreImg)
        self.index = 0
        self.mImgList = []
        return ImgTable

    def getSavePath(self):
        self.labelImgsPath = str(QFileDialog.getExistingDirectory(self, '%s-Open Directory'
         % __appname__, None, QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks))
        if self.labelImgsPath == '':
            return
        self.currentImg = ''
        self.labelImgsPath = self.labelImgsPath.replace('/',os.sep)
        self.imgspath.setText(self.labelImgsPath)
        self.mImgList = scanAllImages(self.labelImgsPath)
        if len(self.mImgList)>0:
            self.index = 0
            src_img = cv2.imdecode(np.fromfile(self.mImgList[0], dtype=np.uint8), -1)
            self.change_image(src_img)
            self.showImg.setText(os.path.basename(self.mImgList[0]))

    def openNextImg(self):
        try:
            if self.index + 1 == len(self.mImgList):
                return
            if self.index == len(self.mImgList):
                return
            self.index = self.index + 1
            self.currentImg = self.mImgList[self.index]
            src_img = cv2.imdecode(np.fromfile(self.currentImg, dtype=np.uint8), -1)
            self.change_image(src_img)
            self.showImg.setText(os.path.basename(self.currentImg))


        except Exception as e:
            print(str(e))

    def openPreImg(self):
        try:
            if self.index == 0:
                return
            if self.index == len(self.mImgList):
                return
            self.index = self.index - 1
            self.currentImg = self.mImgList[self.index]
            src_img = cv2.imdecode(np.fromfile(self.currentImg, dtype=np.uint8), -1)
            self.change_image(src_img)
            self.showImg.setText(os.path.basename(self.currentImg))

        except Exception as e:
            print(str(e))

    def select_image(self):

        path = QFileDialog.getOpenFileName(self, '%s-Open Directory' % __appname__, None,
               'Image File (*.png *.jpg *.bmp *.jpeg *.tif *.ico *.PNG *.JPG *.JPEG *.BMP *.TIF *.ICO)')
        self.labelImgsPath = str(path[0])
        if self.labelImgsPath == '':
            return
        self.imgspath.setText(self.labelImgsPath)
        if self.labelImgsPath.endswith(('.jpg', '.png', '.bmp')):
            src_img = cv2.imdecode(np.fromfile(self.labelImgsPath, dtype=np.uint8), -1)
            self.change_image(src_img)


    def update_image(self):
        if self.src_img is None:
            return
        img = self.process_image()
        self.cur_img = img
        self.graphicsView.update_image(img)

    def change_image(self, img):
        self.src_img = img
        img = self.process_image()
        self.cur_img = img
        self.graphicsView.change_image(img)

    def process_image(self):
        img = self.src_img.copy()
        for i in range(self.useListWidget.count()):
            img = self.useListWidget.item(i)(img)
        return img

    def right_rotate(self):
        self.graphicsView.rotate(90)

    def left_rotate(self):
        self.graphicsView.rotate(-90)

    def histogram(self):
        color = ('b', 'g', 'r')
        for i, col in enumerate(color):
            histr = cv2.calcHist([self.cur_img], [i], None, [256], [0, 256])
            histr = histr.flatten()
            plt.plot(range(256), histr, color=col)
            plt.xlim([0, 256])
        plt.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    app.setStyleSheet(open('./custom/styleSheet.qss', encoding='utf-8').read())
    window = MyApp()
    window.show()
    sys.exit(app.exec_())
